package com.ccnu.demojava.concurrent.thread;

public class RThreadWait extends Thread{
    public int nTickets = 0;
    public Object obj = null;
    
    public void setMutex(Object obj) {
    	this.obj = obj;
    }
   
    @Override
    public void run() {
    	if(obj == null) {
    		System.out.println("mutex is not init, exit the thread");
    		return;
    	}

        for(; ; ) {
        	// 同步扩展重入锁
            synchronized (this) {
                System.out.println("[" + Thread.currentThread().threadId() + "]" + "saled:" + nTickets);
                nTickets++;
                try {
					sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
                if(nTickets == 5) {
            		if(obj!=null) {
                    	try {
                    		synchronized (obj) {
                        		obj.wait();
                    		}
    					} catch (InterruptedException e) {
    						e.printStackTrace();
    					}
            		}
                }
                if(nTickets<=10){
                    continue;
                }
                else{
                    break;
                }
            }
        }
    }   
}
